package com.wuzhishan.news.service.Impl;

import com.wuzhishan.news.mapper.notifyMapper;
import com.wuzhishan.news.mapper.userMapper;
import com.wuzhishan.news.pojo.BlogUser;
import com.wuzhishan.news.pojo.Result;
import com.wuzhishan.news.service.userService;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class userServiceImpl implements userService {
    @Autowired
    private userMapper mapper;
    @Autowired
    private notifyMapper notifyMapper;
    @Value("${STORE_ROOT_PATH}")
    String StoreRootPath; //存储根目录

    /**
     * 用户注册
     * @param formUser
     * @return
     */
    @Override
    public Map<String, Object> register(BlogUser formUser) {
        //查询是否存在当前用户
        BlogUser u1 = mapper.findUserByUsername(formUser.getUsername());
        if(u1!=null){
            //用户名被占用
            return Result.of(100,"用户已存在");
        }
        BlogUser u2 = mapper.findUserByEmail(formUser.getEmail());
        if (u2!=null){
            //邮箱被占用
            return Result.of(101,"邮箱被占用");
        }
        formUser.setAvatar("/store/avatar/2020/04/25/d9f7ac02-cf4f-4629-9cf1-e165657e8171.jpg");   //默认头像
        formUser.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //注册时间
        formUser.setStatus(0);  //0:未激活，1:已激活，2:禁用
        mapper.insertUser(formUser);
        //插入成功后的返回值
        return Result.of(200,"注册成功,请激活后使用!");
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @param session
     * @return
     */
    @Override
    public Result login(String username, String password, HttpSession session) {
        BlogUser user = mapper.findUserByUsername(username);
        if (user==null){
            //用户名不存在
            return Result.of(100,"用户名不存在");
        }
        if(password.equals(user.getPassword())){
            //登录成功
            //将用户信息存入到session中
            session.setAttribute("loginInfo",user);
            //获取出当前用户的通知数目，并返回给用户。
            int totalCount = notifyMapper.notifiesCount(user.getId());
            System.out.println("---------------------"+totalCount);
            session.setAttribute("totalCount",totalCount);
            return Result.of(200,"登录成功，2秒后为您跳转到个人中心");
        }
        //密码错误
        return Result.of(100,"密码错误，请重新输入!");
    }

    /**
     * 更改用户密码
     * @param password
     * @param session
     * @return
     */
    @Override
    public Result updatePassword(String oldPassword, String password, HttpSession session) {
        //因为此时user必然已经登录，否则进不来修改信息页面
        BlogUser user = (BlogUser) session.getAttribute("loginInfo");
        if(oldPassword.equals(user.getPassword())){
            //当前密码输入正确,更新密码
            mapper.updatePassword(user.getId(),password);
            //查找更新后用户的信息，并保存到Session中
            BlogUser u = mapper.findUserByUsername(user.getUsername());
            //更新Session中用户信息
            session.setAttribute("loginInfo",u);
            return Result.of(200);
        }
        //当前密码输入失败，修改密码失败
        return Result.of(300);
    }

    /**
     * 更改用户基本信息
     * @param nickname
     * @param sign
     * @param session
     * @return
     */
    @Override
    public Result updateProfile(String nickname, String sign, HttpSession session) {
        //通过Session获取当前用户信息
        BlogUser user = (BlogUser) session.getAttribute("loginInfo");
        //修改用户信息
        mapper.updateProfile(nickname,sign,user.getId());
        //查找新的用户信息，并保存到Session中
        BlogUser u = mapper.findUserByUsername(user.getUsername());
        //更新Session中用户信息
        session.setAttribute("loginInfo",u);
        return Result.of(200);
    }

    /**
     * 上传图片
     * @param x
     * @param y
     * @param width
     * @param height
     * @param path
     * @param request
     * @return
     */
    public Result updateAvatar(int x, int y, int width, int height, String path, HttpServletRequest request) {
        Date date = new Date();
        String a = "/store/avatar/"
                + new SimpleDateFormat("yyyy").format(date) + "/"
                + new SimpleDateFormat("MM").format(date) + "/"
                + new SimpleDateFormat("dd").format(date) + "/"
                + UUID.randomUUID().toString() + ".jpg";
        File local = new File(StoreRootPath, a);
        File dir = local.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(StoreRootPath, path);
        try {
            Thumbnails.of(file)
                    .sourceRegion(x, y, width, height)
                    .size(width, height)
                    .outputFormat("jpg")
                    .toFile(local);

            BlogUser loginUser = (BlogUser) request.getSession().getAttribute("loginInfo");
            if (loginUser == null) {
                return Result.of(1); //1代表未登录
            }

            BlogUser user = mapper.getOneById(loginUser.getId());
            user.setAvatar(a);
            mapper.updateAvatar(user.getId(),a);
            request.getSession().setAttribute("loginInfo", user);
            return Result.of(2); //2代表修改成功
        } catch (Exception e) {
            e.printStackTrace();
            return Result.of(3, e.toString());//3代表异常
        }
    }
}
